#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "EaseLocationViewController.h"
#import "UIViewController+HUD.h"
#import "EaseLocalDefine.h"
static EaseLocationViewController *defaultLocation = nil;
@interface EaseLocationViewController () <MKMapViewDelegate,CLLocationManagerDelegate>
{
    MKMapView *_mapView;
    MKPointAnnotation *_annotation;
    CLLocationManager *_locationManager;
    CLLocationCoordinate2D _currentLocationCoordinate;
    BOOL _isSendLocation;
    UIButton *_sendButton;
}
@property (strong, nonatomic) NSString *addressString;
@end
@implementation EaseLocationViewController
@synthesize addressString = _addressString;
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _isSendLocation = YES;
    }
    return self;
}
- (instancetype)initWithLocation:(CLLocationCoordinate2D)locationCoordinate
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _isSendLocation = NO;
        _currentLocationCoordinate = locationCoordinate;
    }
    return self;
}
+ (instancetype)defaultLocation
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defaultLocation = [[EaseLocationViewController alloc] initWithNibName:nil bundle:nil];
    });
    return defaultLocation;
}
-(void)itemback{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = m1_bg_color;
    self.title = NSEaseLocalizedString(@"location.messageType", @"location message");
    
    UIView *nav = [[UIView alloc]init];
    nav.backgroundColor = m1_bg_color;
    nav.frame = CGRectMake(0, 0, SCREENHEIGHT, m1_NAV_HEIGHT);
    [self.view addSubview:nav];
    
    
    UIButton *backItem = [UIButton buttonWithType:UIButtonTypeCustom];
    [backItem setImage:[[UIImage imageNamed:@"black_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:0];
    backItem.frame = CGRectMake(0, iPhoneX?44:20, 60, 44);
    [backItem addTarget:self action:@selector(itemback) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backItem];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = m1_boldFont(17);
    titleLabel.text =  NSEaseLocalizedString(@"location.messageType", @"location message");
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(70, iPhoneX?44:20, SCREENWIDTH-140, 44);
    titleLabel.textColor = [UIColor m1_colorHex:0x333333];
    [nav addSubview:titleLabel];
    
    _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, m1_NAV_HEIGHT, SCREENWIDTH, SCREENHEIGHT-m1_NAV_HEIGHT)];
    _mapView.delegate = self;
    _mapView.mapType = MKMapTypeStandard;
    _mapView.zoomEnabled = YES;
    [self.view addSubview:_mapView];
    if (_isSendLocation) {
        _mapView.showsUserLocation = YES;
        _sendButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREENWIDTH-60, iPhoneX?44:20, 60, 44)];
        [_sendButton setTitle:NSEaseLocalizedString(@"send", @"Send") forState:UIControlStateNormal];
        _sendButton.titleLabel.font = m1_font(15);
        _sendButton.accessibilityIdentifier = @"send_location";
        [_sendButton setTitleColor:[UIColor m1_colorHex:0x999999] forState:UIControlStateNormal];
        [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [_sendButton addTarget:self action:@selector(sendLocation) forControlEvents:UIControlEventTouchUpInside];
        [nav addSubview:_sendButton];
        _sendButton.userInteractionEnabled = NO;
        [self startLocation];
    }
    else{
        [self removeToLocation:_currentLocationCoordinate];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    __weak typeof(self) weakSelf = self;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray *array, NSError *error) {
        if (!error && array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            weakSelf.addressString = placemark.name;
            [self removeToLocation:userLocation.coordinate];
        }
    }];
}
- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    [self hideHud];
    if (error.code == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                            message:[error.userInfo objectForKey:NSLocalizedRecoverySuggestionErrorKey]
                                                           delegate:nil
                                                  cancelButtonTitle:NSEaseLocalizedString(@"ok", @"OK")
                                                  otherButtonTitles:nil, nil];
        [alertView show];
    }
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [_locationManager requestWhenInUseAuthorization];
            }
            break;
        case kCLAuthorizationStatusDenied:
        {
        }
        default:
            break;
    }
}
#pragma mark - public
- (void)startLocation
{
    if([CLLocationManager locationServicesEnabled]){
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = 5;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationManager requestWhenInUseAuthorization];
        }
    }
    if (_isSendLocation) {
        [_sendButton setTitleColor:[UIColor m1_colorHex:0x999999] forState:UIControlStateNormal];
        _sendButton.userInteractionEnabled = NO;
    }
    [self showHudInView:self.view hint:NSEaseLocalizedString(@"location.ongoning", @"locating...")];
}
-(void)createAnnotationWithCoords:(CLLocationCoordinate2D)coords
{
    if (_annotation == nil) {
        _annotation = [[MKPointAnnotation alloc] init];
    }
    else{
        [_mapView removeAnnotation:_annotation];
    }
    _annotation.coordinate = coords;
    [_mapView addAnnotation:_annotation];
}
- (void)removeToLocation:(CLLocationCoordinate2D)locationCoordinate
{
    [self hideHud];
    _currentLocationCoordinate = locationCoordinate;
    float zoomLevel = 0.01;
    MKCoordinateRegion region = MKCoordinateRegionMake(_currentLocationCoordinate, MKCoordinateSpanMake(zoomLevel, zoomLevel));
    [_mapView setRegion:[_mapView regionThatFits:region] animated:YES];
    if (_isSendLocation) {
        [_sendButton setTitleColor:[UIColor m1_colorHex:0x333333] forState:UIControlStateNormal];
        _sendButton.userInteractionEnabled = YES;
    }
    [self createAnnotationWithCoords:_currentLocationCoordinate];
}
- (void)sendLocation
{
    if (_delegate && [_delegate respondsToSelector:@selector(sendLocationLatitude:longitude:andAddress:)]) {
        [_delegate sendLocationLatitude:_currentLocationCoordinate.latitude longitude:_currentLocationCoordinate.longitude andAddress:_addressString];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
@end
